#include"logger.h"
#include<time.h>
#include<string>
#include<iostream>

//日志单例
Logger& Logger::GetInstance()
{
    static Logger logger;
    return logger;
}

//构造
Logger::Logger()
{
    //启动写日志线程
    std::thread wirte([&]()
    {
        while(1)
        {
            //获取日期
            time_t now=time(nullptr);
            tm* nowtm=localtime(&now);

            char file_name[128];
            sprintf(file_name,"%d_%d_%d-log.txt",nowtm->tm_year+1900,nowtm->tm_mon+1,nowtm->tm_mday);

            FILE* pf=fopen(file_name,"a+");
            if(pf==nullptr)
            {
                std::cout << "logger file" << file_name << "open error!" << std::endl;\
                exit(EXIT_FAILURE);
            }
            
            std::string msg=_lckque.Pop();
            
            char time[128]={0};
            sprintf(time,"%d:%d:%d [%s] => ",nowtm->tm_year+1900,nowtm->tm_mon+1,nowtm->tm_mday,(_loglevel==INFO?"info":"error"));
            msg.insert(0,time);
            msg+="\n";
            fputs(msg.c_str(),pf);
            fclose(pf);
        }
    });
    //分离线程
    wirte.detach();
}

//设置日志等级
void Logger::SetLogLevel(LogLevel level)
{
    _loglevel=level;
}

//日志写入
void Logger::Log(std::string msg)
{
    _lckque.Push(msg);
}